package com.mframe.web;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mframe.system.LoginInfo;
import com.mframe.system.MFrameConstant;

/**
 * remark: 若要实现同一浏览器中的session互相不干扰~应建立新的表
 * 
 * @author cuijr session管理
 * 
 */
public class SessionManager {
	// 这里的threadLocal是一个线程池,获取到的session,相当于拿出来一个session,不用重新赋值给threadLocal
	private static final ThreadLocal<HttpSession> sessionT = new ThreadLocal<HttpSession>();
	private static Logger logger = LoggerFactory
			.getLogger(SessionManager.class);

	public static void setSession(HttpSession session) {
		sessionT.set(session);
	}

	public static HttpSession getSession() {
		return (HttpSession) sessionT.get();
	}

	/**
	 * remark:为这个session设置属性
	 * 
	 * @param s
	 * @param obj
	 */
	public static void setAttribute(String s, Object obj) {
		HttpSession session = (HttpSession) sessionT.get();
		if (session != null) {
			session.setAttribute(s, obj);
		} else if (logger.isDebugEnabled()) {
			// debug模式下才能看到的
			logger.debug("session not exist can not set attribute with key = '"
					+ s + "' value = [" + obj + "]");
		}
	}

	/**
	 * 获取线程池当中的session的属性
	 * 
	 * @param s
	 * @return
	 */
	public static Object getAttribute(String s) {
		HttpSession session = (HttpSession) sessionT.get();
		logger.debug("取值线程:" + session.toString());
		if (session != null) {
			return session.getAttribute(s);
		} else if (logger.isDebugEnabled()) {
			// debug模式下才能看到的
			logger.debug("session not exist could not get attribute '" + s
					+ "'");
		}
		return null;
	}

	/**
	 * 清除session对象
	 */
	public static void clean() {
		logger.debug("clean sessionManager");
		sessionT.remove();
	}

	/**
	 * 注销用户
	 */
	public static void logout() {
		HttpSession session = (HttpSession) sessionT.get();
		if (session == null)
			return;
		try {
			//注销用户
			if(session.getAttribute(MFrameConstant.SESSION_LOGIN_NAME) !=null){
				session.setAttribute(MFrameConstant.SESSION_LOGIN_NAME, null);
				session.removeAttribute(MFrameConstant.SESSION_LOGIN_NAME);
			}
		} catch (Exception e) {
			logger.info("login out error");
		}
		clean();
		session.invalidate();
		if (logger.isDebugEnabled())
			logger.debug("user logout.");
	}

	/**
	 * 把用户信息设置到session中
	 * 
	 * @param <T>
	 * @param loginInfo
	 */
	public static <T extends LoginInfo> void setLoginInfo(T loginInfo) {
		if (logger.isDebugEnabled()) {
			logger.debug("bind user [" + loginInfo.getStaffName()
					+ "] to current session :" + sessionT.get());
		}
		// setAttribute
		setAttribute(MFrameConstant.SESSION_LOGIN_NAME, loginInfo);
	}
}
